package com.cmge.ad.spider.pipeline;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import com.cmge.ad.model.Article;
import com.cmge.ad.service.MainService;
import com.cmge.ad.util.JsonUtil;

/**
 * @desc	抓取内容存放到数据库中
 * @author	ljt
 * @time	2015-1-4 上午10:48:30
 */
@Component
public class MysqlArticlePipeline implements Pipeline{
	
	@Autowired
	private MainService mainService;
	
	static{
//		JdbcUtils.getConnection();
	}
	
	@Override
	public void process(ResultItems resultItems, Task task) {
		Integer type = (Integer)resultItems.get("type");
		if(type != null && type.intValue() == 1){
			// article list
			List<Article> articleList = (List<Article>)resultItems.get("articleList");
			if(null != articleList && articleList.size() > 0){
				String sql = "insert into t_article_src (content, minImageUrl,maxImageUrl,type,source,answer,createTime) " +
						"values (?,?,?,?,?,?,now())";
				for(Article article : articleList){
					System.out.println(JsonUtil.toJson(article));
					try {
						List<Object> params = new ArrayList<Object>();
						params.add(article.getContent());
						params.add(article.getMinImageUrl());
						params.add(article.getMaxImageUrl());
						params.add(article.getType());
						params.add(article.getSource());
						params.add(article.getKey());
						JdbcUtils.updateByPreparedStatement(sql, params);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		if(type != null && type.intValue() == 2){
			// article list
			Article article = (Article)resultItems.get("article");
			if(null != article){
				String sql = "insert into t_article_src (content, minImageUrl,maxImageUrl,type,source,answer,createTime) " +
						"values (?,?,?,?,?,?,now())";
				System.out.println(JsonUtil.toJson(article));
				try {
					List<Object> params = new ArrayList<Object>();
					params.add(article.getContent());
					params.add(article.getMinImageUrl());
					params.add(article.getMaxImageUrl());
					params.add(article.getType());
					params.add(article.getSource());
					params.add(article.getKey());
//					JdbcUtils.updateByPreparedStatement(sql, params);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
}